//
//  PKProductMainViewController.m
//  PianKe
//
//  Created by ybq on 15/12/21.
//  Copyright © 2015年 B7_Young. All rights reserved.
//

#import "PKProductMainViewController.h"
#import "PKProductMianListTableViewCell.h"


@interface PKProductMainViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *datasource;   // 给表视图提供数据的数组
@property (nonatomic, strong) FMDatabase *db;   // FMDB里面的数据库,一个db就是一个数据库,每个数据库里可以放很多张表
@property (nonatomic, assign) NSInteger requestStart;

@property (nonatomic, strong) UILabel *titleLabel;  // 刷新的时候给我们提示的label
@property (nonatomic, assign) BOOL isRefreshing;

@end

@implementation PKProductMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self changeNavViewTitle];
    _requestStart = 0;
    
#pragma mark MJRefresh
//    _isRefreshing = NO;
//
//    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, kWidth, 50)];
//    _titleLabel.textAlignment = NSTextAlignmentCenter;
//    _titleLabel.backgroundColor = [UIColor grayColor];
    
    // Do any additional setup after loading the view.
    
    // 请求数据
    [self requestData];
    
    _datasource = [NSMutableArray array];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    // MJRefresh
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _requestStart = 0;
        [self requestData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _requestStart += 10;
        [self requestData];
    }];
    
    self.tableView.rowHeight = (kWidth - 40) * 300 / 608 + 50;
    [self.tableView registerClass:[PKProductMianListTableViewCell class] forCellReuseIdentifier:@"PKProductMianListTableViewCell"];
    [self.view addSubview:self.tableView];
    
//    [self.tableView addSubview:_titleLabel];
#pragma mark -- FMDB
    // 创建我们的数据库的路径,同时拼接数据库的名字
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"PKDataBase.db"];
    // 根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    NSLog(@"%@",path);
    
    // 调用open方法打开数据库,成功返回YES,失败返回NO
    if ([_db open]) {
        NSLog(@"数据库打开成功");
    } else {
        NSLog(@"数据库打开失败");
    }
    // 调用db的executeUpdate,这个方法的参数就是sql语句
    [_db executeUpdate:@"CREATE TABLE ProductList (buyurl text, contentid text, coverimg text, title text)"];
    // 执行查找的操作,调用的方法是executeQuery,参数是sql的查找语句,会返回一个FMResult类型的结果
    FMResultSet *result = [_db executeQuery:@"SELECT * FROM ProductList"];
    // 类似链表结构
    while ([result next]) {
        NSString *buyurl = [result stringForColumn:@"buyurl"];
        NSString *contentid = [result stringForColumn:@"contentid"];
        NSString *coverimg = [result stringForColumn:@"coverimg"];
        NSString *title = [result stringForColumn:@"title"];
//        result intForColumn:@"age";   int类型
        PKProductMainListModel *model = [[PKProductMainListModel alloc] init];
        model.buyurl = buyurl;
        model.contentid = contentid;
        model.coverimg = coverimg;
        model.title = title;
        [_datasource addObject:model];
    }
    
}

// 自定义请求数据的方法
- (void)requestData {
    _isRefreshing = YES;
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"07EBFC18-9BF8-47D1-9FEA-79BBF44D4C9E";
    parDic[@"limit"] = @"10";
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",_requestStart];
    parDic[@"version"] = @"3.0.6";
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/pub/shop" parDic:parDic Method:POST finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *listArray = dataDic[@"data"][@"list"];
        // 新增前删除旧数据
        [_db executeUpdate:@"DELETE FROM ProductList"];
        // 刷新的时候 有了新数据要把旧数据情况,否则会造成数据重复
        if (_requestStart == 0) {
            [_datasource removeAllObjects];
        }
        for (NSDictionary *dic in listArray) {
            PKProductMainListModel *model = [[PKProductMainListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_datasource addObject:model];
            // FMDB插入的时候必须是一个对象,如果表里面一个字段是int类型,插入的时候需要插入一个NSNumber对象
            [_db executeUpdate:@"INSERT INTO ProductList (buyurl, contentid, coverimg, title) VALUES (?, ?, ?, ?)",model.buyurl, model.contentid, model.coverimg, model.title];
            
        }
#pragma mark MJRefresh
//        _titleLabel.text = @"";
//        [self.tableView setContentInset:UIEdgeInsetsZero];
//        _isRefreshing = NO;
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        
    }];
    
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api2.pianke.me/pub/shop"]];
//    [request setHTTPMethod:@"POST"];
//    [request setHTTPBody:[@"auth=&client=1&deviceid=F2BB0D94-98EE-4D6E-B835-E1E258643C88&limit=10&start=0&version=3.0.6" dataUsingEncoding:NSUTF8StringEncoding]];
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        if (connectionError == nil) {
//            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
//            NSArray *listArray = dataDic[@"data"][@"list"];
//            for (NSDictionary *dic in listArray) {
//                PKProductMainListModel *model = [[PKProductMainListModel alloc] init];
//                [model setValuesForKeysWithDictionary:dic];
//                [_datasource addObject:model];
//            }
//            [_listTableView reloadData];
//        }
//    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"网管是傻逼");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PKProductMianListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PKProductMianListTableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PKProductMainListModel *model = _datasource[indexPath.row];
    cell.model = model;
    [cell.button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.button.tag = 100 + indexPath.row;
    return cell;
}

- (void)buttonAction:(UIButton *)sender {
//    PKProductMianListTableViewCell *cell = (PKProductMianListTableViewCell *)sender.superview.superview;
//    NSIndexPath *indexPath = [_listTableView indexPathForCell:cell];
//    PKProductMainListModel *model = _datasource[indexPath.row];
    
    // tag值实现
    PKProductMainListModel *model = _datasource[sender.tag - 100];
    // 打开浏览器
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.buyurl]];
}


#pragma mark 实现MJRefresh

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    // 得到tableView的Y轴偏移量
//    CGFloat y = scrollView.contentOffset.y;
//    NSLog(@"%f",y);
//    // 被拖拽时不刷新,只改变label上的文字
//    if (scrollView.isDragging) {
//        if (y < 0 && y > -50) {
//            _titleLabel.text = @"再下拉一点就可以刷新了";
//        }
//        if (y <= -50) {
//            _titleLabel.text = @"松开手就可以刷新了";
//        }
//    } else {
//        if (y < -50) {
//            if (_isRefreshing) {
//                return;
//            }
//            _titleLabel.text = @"正在刷新";
//            // 松手之后让tableView一直显示label,让tableView下沉50
//            [scrollView setContentInset:UIEdgeInsetsMake(50, 0, 0, 0)];
//            _requestStart = 0;
//            [self requestData];
//        }
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
